import Vue from "vue";
import VueRouter from "vue-router";
import store from "../store"; 

Vue.use(VueRouter);

// 路由配置
const routes = [
  // 登录页面路由
  {
    path: "/login",
    name: "Login",
    component: () => import("@/views/Login.vue"),
    meta: { requiresAuth: false }  // 不需要认证
  },
  // 注册页面路由
  {
    path: "/register",
    name: "Register",
    component: () => import("@/views/Register.vue"),
    meta: { requiresAuth: false }  // 不需要认证
  },
  // 主布局路由
  {
    path: "/",
    component: () => import("@/views/Layout.vue"),
    meta: { requiresAuth: true },  // 需要认证
    children: [
      // 首页仪表盘
      {
        path: "",
        name: "Dashboard",
        component: () => import("@/views/Dashboard.vue"),
        meta: { title: "首页" }
      },
      // 暂存柜管理路由组
      {
        path: "cabinets",
        component: () => import("@/views/cabinets/Index.vue"),
        meta: { title: "暂存柜" },
        children: [
          // 默认重定向到 A 区
          {
            path: '',
            redirect: { name: 'AreaCabinets', params: { area: 'A' } }
          },
          // 区域视图
          {
            path: ':area',
            name: 'AreaCabinets',
            component: () => import("@/views/cabinets/Area.vue"),
            meta: { title: route => `${route.params.area}区` },
            children: [
              // 排视图
              {
                path: ':row',
                name: 'RowCabinets',
                component: () => import("@/views/cabinets/Row.vue"),
                meta: { title: route => `${route.params.row}排` },
                children: [
                  // 柜子详情视图
                  {
                    path: ':cabinetId',
                    name: 'CabinetDetail',
                    component: () => import("@/views/cabinets/Detail.vue"),
                    meta: { title: route => `${route.params.cabinetId}号柜` }
                  }
                ]
              }
            ]
          }
        ]
      },
      // 使用记录页面
      {
        path: "history",
        name: "History",
        component: () => import("@/views/records/Index.vue"),
        meta: { title: "使用记录" }
      },
      // 修改密码页面
      {
        path: "change-password",
        name: "ChangePassword",
        component: () => import("@/views/user/ChangePassword.vue"),
        meta: { title: "修改密码" }
      },
      // 使用说明页面
      {
        path: "instructions",
        name: "Instructions",
        component: () => import("@/views/user/Instructions.vue"),
        meta: { title: "使用说明" }
      },
      // 管理员功能路由组
      {
        path: "admin",
        name: "Admin",
        component: () => import("@/views/admin/Index.vue"),
        meta: { title: "系统管理", requiresAdmin: true },  // 需要管理员权限
        children: [
          // 柜子管理页面
          {
            path: "cabinets",
            name: "CabinetManagement",
            component: () => import("@/views/admin/CabinetManagement.vue"),
            meta: { title: "柜子管理" }
          },
          // 用户管理页面
          {
            path: "users",
            name: "UserManagement",
            component: () => import("@/views/admin/Users.vue"),
            meta: { title: "用户管理" }
          }
        ]
      }
    ]
  }
];

const router = new VueRouter({
  mode: "history",
  base: process.env.BASE_URL,
  routes
});

// 路由守卫
router.beforeEach((to, from, next) => {
  const isAuthenticated = store.getters.isAuthenticated;
  const user = store.state.user;

  // 设置页面标题
  let pageTitle = "暂存柜管理系统";  // 默认标题

  // 根据路由元信息设置页面标题
  if (to.matched.length > 0) {
    for (let i = to.matched.length - 1; i >= 0; i--) {
      const record = to.matched[i];
      if (record.meta && record.meta.title) {
        if (typeof record.meta.title === 'function') {
           pageTitle = record.meta.title(to);
        } else {
           pageTitle = record.meta.title;
        }
        break; 
      }
    }
  }

  // 添加系统名称后缀
  if (to.path !== '/login' && to.path !== '/register' && !pageTitle.includes("暂存柜管理系统")) {
     pageTitle = `${pageTitle} - 暂存柜管理系统`;
  }
  document.title = pageTitle;

  // 路由权限控制
  if (to.matched.some((record) => record.meta.requiresAuth)) {
    // 需要认证但未登录
    if (!isAuthenticated) {
      next({
        path: "/login",
        query: { redirect: to.fullPath }  // 保存目标路由，登录后跳转
      });
    } else {
      // 检查是否需要管理员权限
      if (to.matched.some((record) => record.meta.requiresAdmin)) {
        if (user && user.role === "admin") {
          next();  // 是管理员，允许访问
        } else {
          // 不是管理员，显示提示并阻止访问
          alert("请以管理员身份登录访问此页面");
          next(false);
        }
      } else {
        next();  // 不需要管理员权限，允许访问
      }
    }
  } else {
    next();  // 不需要认证，允许访问
  }
});

export default router;
